package com.aaa.controller;

import com.aaa.entity.Menu;
import com.aaa.entity.MyReturn;
import com.aaa.service.LoginService;
import com.aaa.service.MenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import java.util.List;
import java.util.Map;

/**
 * @author yudejie2020
 */
@Controller
public class LoginController extends BaseController {
    @Autowired
    LoginService loginService;
    @Autowired
    MenuService menuService;
    MyReturn myReturn=new MyReturn();
    @RequestMapping("login.do")
    @ResponseBody
    public MyReturn login(@RequestBody Map<String,Object> map, HttpSession session) {

        boolean checkUser=loginService.checkUser(map);

        //登录等待
        try {
            //休眠10秒
            Thread.sleep(500);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        if (checkUser){
            //登录成功之前，增强处理，将登录名保存到session中
            Map<String,Object> userinfo=loginService.findUserInfoByName(map);

            //清除密码和盐值
            userinfo.remove("password");
            userinfo.remove("salt");
            session.setAttribute("userinfo",userinfo);
            System.out.println(userinfo);
            //登录成功之前，增强处理，将登录用户对应的菜单保存到session中
            Map<String, List<Menu>> menuMap = menuService.findMenuByUsername(map.get("searchUserName").toString());
            session.setAttribute("menuMap",menuMap);
            //登录成功
            return super.getSuccessReturn(myReturn);
        }
        return super.getFailReturn(myReturn);
    }

    @RequestMapping("logout.do")
    public String logout(HttpSession session){
        //session失效
        session.invalidate();
        //跳转到登录页面
        return "redirect:/login.jsp";
    }
}
